def test(fn):
= [1,8,6,2,5,4,8,3,7]
height = 49
expected = fn(height)
actual assert actual == expected
= [1,1]
height = 1
expected = fn(height)
actual assert actual == expected
Problem Source: Leetcode
Problem Description
You are given an integer array height
of length n
. There are n vertical lines drawn such that the two endpoints of the ith
line are (i, 0)
and (i, height[i])
.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
tests
Solution
- Time Complexity:
O(n)
- Space Complexity:
O(1)
from typing import List
def maxArea(height: List[int]) -> int:
= 0, len(height)-1 # start at each end
l,r = 0
maxV
# Iterate through half, so you stop when pointers meet somewhere in middle
while l < r:
= height[l],height[r]
lh, rh
# calculate current area and keep if bigger
= max(maxV, (r-l) * min(lh,rh))
maxV
# move pointer on smallest side
if lh < rh:
+=1
lelse:
-=1
rreturn maxV
test(maxArea)